using System;
using System.Text;
using System.IO;

namespace ThalesHsmComms
{
	public class GenerateSecureMessage : WSMMsg
	{
		String modeFlag = "0";
		String cipherTextDelimeter = ";";
		
		String pan;
		String seqNo;
		String atc;
		String clearText;
		String issuerMasterKey;
		
		
		public String EmvMAC{get;private set;}
		String panPanSeq;

		public GenerateSecureMessage (String pan, String seqNo, String atc, String clearText, String issuerMasterKey)
			:base("KU")
		{
			this.pan = pan;
			this.seqNo =seqNo;
			this.atc = atc;
			this.clearText = clearText;
			this.issuerMasterKey = "U"+issuerMasterKey;
			
			this.panPanSeq = pan.Substring(pan.Length - 14) + seqNo.Substring(seqNo.Length - 2);
		}

		protected override void Encode()
		{
			MemoryStream data = new MemoryStream();
			try 
			{
				
				// pack command code
				byte[] tmp = Encoding.ASCII.GetBytes(this.commandCode);
				data.Write(tmp,0,tmp.Length);
				
				//pack mode flag
				tmp = Encoding.ASCII.GetBytes(this.modeFlag);
				data.Write(tmp,0,tmp.Length);
			
				tmp = Encoding.ASCII.GetBytes("1");
				data.Write(tmp,0,tmp.Length);
	
				//pack issuer master key
				tmp = Encoding.ASCII.GetBytes(this.issuerMasterKey);
				data.Write(tmp,0,tmp.Length);
				
				//pack pan pan seq
				tmp = HexConverter.FromHex2Binary(this.panPanSeq);
				data.Write(tmp,0,tmp.Length);
			
				
				//pack atc
				tmp = HexConverter.FromHex2Binary(this.atc);
				data.Write(tmp,0,tmp.Length);
				
				
				// pack clear text message
				tmp = Encoding.ASCII.GetBytes("000C");
				data.Write(tmp,0,tmp.Length);

				tmp = HexConverter.FromHex2Binary(this.clearText);
				data.Write(tmp,0,tmp.Length);

				
				// pack delimeter
				tmp = Encoding.ASCII.GetBytes(this.cipherTextDelimeter);
				data.Write(tmp,0,tmp.Length);
				
				this.requestData = data.ToArray();

				
			} 
			catch (IOException ex) 
			{
				Console.WriteLine(ex);
			}
		}

		override protected void Decode() 
		{
			this.EmvMAC = this.GetNextBytesFromResponse(8);
		}
	}
}

